package com.nlx.notes.module.service.impl.statistics;

import cn.hutool.core.collection.CollUtil;
import com.nlx.notes.module.bean.dto.querydb.StatisticsQueryDTO;
import com.nlx.notes.module.bean.vo.statistics.CategoryMonthStatisticsVO;
import com.nlx.notes.module.core.util.AmountConverterUtils;
import com.nlx.notes.module.core.util.DateUtils;
import com.nlx.notes.module.service.ICategoriesService;
import com.nlx.notes.module.service.ICategoryMonthStatisticsService;
import com.nlx.notes.module.service.statistics.CategoryMonthStatisticsManageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CategoryMonthStatisticsManageServiceImpl implements CategoryMonthStatisticsManageService {

    final ICategoryMonthStatisticsService categoryMonthStatisticsService;

    final ICategoriesService categoriesService;


    @Override
    public List<CategoryMonthStatisticsVO> monthStatisticsMetrics(StatisticsQueryDTO statisticsQueryDTO) {
        log.info("查询用户的分类月度统计数据，用户：{}", statisticsQueryDTO.getUserId());
        if(null == statisticsQueryDTO.getMonth()){
            statisticsQueryDTO.setMonth(DateUtils.formatCurrentMonth());
        }
        List<CategoryMonthStatisticsVO> categoryMonthStatistics = categoryMonthStatisticsService.findByMonth(statisticsQueryDTO);
        if(CollUtil.isEmpty(categoryMonthStatistics)){
            return Collections.emptyList();
        }

        int totalAmount = categoryMonthStatistics.stream()
                .mapToInt(item -> {
                    try {
                        return item.getAmountInt();
                    } catch (NumberFormatException e) {
                        return 0;
                    }
                }).sum();

        if (totalAmount == 0) {
            categoryMonthStatistics.forEach(item -> item.setPercent("0.00"));
        }else{
            for (CategoryMonthStatisticsVO item : categoryMonthStatistics) {
                item.setAmount(AmountConverterUtils.convertFenToYuan(item.getAmountInt()));
                BigDecimal percent = BigDecimal.valueOf(item.getAmountInt())
                        .multiply(BigDecimal.valueOf(100))
                        .divide(BigDecimal.valueOf(totalAmount), 2, BigDecimal.ROUND_HALF_UP);
                item.setPercent(percent.toString());  // 如 "23.45"
            }
        }
        categoryMonthStatistics.sort(Comparator.comparing(CategoryMonthStatisticsVO::getAmountInt).reversed());
        return categoryMonthStatistics;
    }
}
